package com.harmontronics.hanma.paas.paas.domain.app.service;

import com.harmontronics.hanma.paas.paas.domain.app.service.tools.HttpClient;
import com.harmontronics.hanma.paas.paas.domain.app.service.tools.SqlClient;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;

/**
 * @author ldb
 */
@Service("scriptExecutor")
@Scope(SCOPE_PROTOTYPE)
public class ScriptExecutor {

    @Autowired
    private SqlClient sqlClient;

    private DelegateExecution execution;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    private HttpClient httpClient;

    public ScriptExecutor withFlowableExecution(DelegateExecution execution) {
        this.execution = execution;
        return this;
    }


    public Object execute(String code, Map<String, Object> properties) {
        Binding intBinding = new Binding();
        GroovyShell shell = new GroovyShell(intBinding);
        Script script = shell.parse(code);
        setProperties(script, properties);
        return script.invokeMethod("main", null);
    }


    private void setProperties(Script script, Map<String, Object> properties) {
        for (Map.Entry<String, Object> entry : properties.entrySet()) {
            script.setProperty(entry.getKey(), entry.getValue());
        }
        if (execution != null) {
            script.setProperty("execution", execution);
        }
        script.setProperty("sqlClient", sqlClient);

        script.setProperty("redisClient", stringRedisTemplate);
        script.setProperty("httpClient", httpClient);
    }


    public Object execute(File file, Map<String, Object> properties) throws IOException {
        Binding binding = new Binding();
        GroovyShell shell = new GroovyShell(binding);
        Script script = shell.parse(file);
        setProperties(script, properties);
        return script.invokeMethod("main", null);
    }


}
